import React, {useEffect, useState} from "react";
import {Box, Center, Loader, Text} from "@mantine/core";
import Lottie from "lottie-react";

interface LottieWrapperProps {
  simulationState: "IDLE" | "RUNNING" | "FINISHED";
  height?: number | string;
  width?: number | string;
}

export default function LottieWrapper({
  simulationState,
  height = 100,
  width = "100%",
}: LottieWrapperProps) {
  const [animationData, setAnimationData] = useState<any>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    const loadAnimation = async () => {
      setError(false);
      setAnimationData(null);
      try {
        // 直接用 simulationState 来构造文件路径
        const res = await fetch(`/lottie/${simulationState}.json`);
        if (!res.ok) throw new Error("加载失败");
        const json = await res.json();
        setAnimationData(json);
      } catch (err) {
        setError(true);
      }
    };

    loadAnimation();
  }, [simulationState]);

  if (error) {
    return (
      <Center h={height} w={width}>
        <Text c="red">动画加载失败</Text>
      </Center>
    );
  }

  if (!animationData) {
    return (
      <Center h={height} w={width}>
        <Loader color="blue" />
      </Center>
    );
  }

  return (
    <Box h={height} w={width}>
      <Lottie
        animationData={animationData}
        loop
        autoplay
        style={{
          width: "100%", // 动画宽度占满父容器宽度
          height: "100%", // 动画高度占满设置的200px高度
          objectFit: "contain", // 保证动画宽高比不变，适应父容器
        }}
      />
    </Box>
  );
}
